package com.yyq.sos.util;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.pojo.PermissionVO;

public class PermissionsUtil {

	 public static boolean checkPermissionByCode(HttpSession session, String resCode, String optCode)
	  {
		 LoginUser user = (LoginUser) session.getAttribute(
					Constants.LOGIN_USER);
		 
		 if (user.getUserId().intValue()==1)
		 {
			 return true;
		 }
	    if ((optCode == null) || (resCode == null))
	      return false;
	    resCode = resCode.trim();
	    optCode = optCode.trim();
	    if ((resCode.equals("")) || (optCode.equals("")))
	      return false;
	    if (user == null)
	    {
	      return false;
	    }
	    
	    Map<String,List<String>> permissions = (Map<String,List<String>>)session.getAttribute(Constants.PERMISSION);

	    if ((permissions == null) || (permissions.size() == 0)) {
	      return false;
	    }

	    List<String> perms = permissions.get(resCode);
	    String[] optCodes = optCode.split("&&");
	    String[] optCodesOr = optCode.split("\\|\\|");
	    if(optCodesOr.length > 1){
	    	for(int i=0;i<optCodesOr.length;i++){
	    		for(int j=0;perms != null && j<perms.size();j++){
	    			if(optCodesOr[i].equals(perms.get(j))){
	    				return true;
	    			}
	    		}
	    	}
	    }else if(optCodes.length>1){
	    	for(int j=0;j<optCodes.length;j++){
	    		boolean flag = false;
	    		for(int i=0;perms != null && i<perms.size();i++){
	    			if(optCodes[j].equals(perms.get(i))){
	    				flag = true;
	    				break;
	    			}
	    		}
	    		if(!flag){
	    			return false;
	    		}
	    	}
	    	return true;
	    }else{
	    	for(int i=0;perms != null && i<perms.size();i++){
	    		if(optCode.equals(perms.get(i))){
	    			return true;
	    		}
	    	}
	    }
	    
	    return false;
	  }

	  public static boolean checkPermissionByCode(HttpSession session, String resCode)
	  {
		  LoginUser user = (LoginUser) session.getAttribute(
					Constants.LOGIN_USER);
		  if (user.getUserId().intValue()==1)
		  {
			  return true;
		  }
	    if (resCode == null)
	      return false;
	    if (user == null)
	    {
	      return false;
	    }
	    Map<String,List<String>> permissions = (Map<String,List<String>>)session.getAttribute(Constants.PERMISSION);

	    if ((permissions == null) || (permissions.size() == 0)) {
	      return false;
	    }
	    resCode = resCode.trim();
	    List<String> perms = permissions.get(resCode);
	    if(perms != null && perms.size()>0){
	    	return true;
	    }
	    
	    return false;
	  }
}
